
//
//  QueryTypeSelectionController.m
//  PublicInfo
//
//  Created by enghou on 2018/1/9.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

#import "ChooseObjectTypeViewController.h"
#import "UILabel+CaculateSize.h"
#import "NetWorkerManager.h"
#import "SubTypeItemModel.h"
#import "TypeListModel.h"
#import "PopulationContainerViewController.h"
#import "ServiceSubTypeModel.h"
#import "ServiceBigTypeModel.h"
@interface ChooseObjectTypeViewController ()

@property(nonatomic,strong)NSMutableArray *peopleRelated;

@property(nonatomic,strong)NSMutableArray *financialRelated;

@property(nonatomic,strong)NSMutableArray *btnsArray;

@property(nonatomic,strong)UILabel *descLabel;
@end

@implementation ChooseObjectTypeViewController

-(instancetype)init{
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Service" bundle:[NSBundle mainBundle]];
    return [story instantiateViewControllerWithIdentifier:@"ChooseObjectTypeViewController"];
}

-(NSDictionary *)param{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if ([self.selectedBusiness count] > 0) {
        [self.selectedBusiness enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *key = [NSString stringWithFormat:@"populationTypes[%lu]",idx];
            [param setObject:obj forKey:key];
        }];
    }else{
        [self alertSomes:@"请选择人口业务信息!"];
        return nil;
    }
    if ([self.selectedOrgId length] > 0) {
        [param setObject:self.selectedOrgId forKey:@"alongRailways[0].orgId"];
    }
    if ([self.orgType length] > 0) {
        [param setObject:self.orgType forKey:@"alongRailways[0].type"];
    }
    return param;
}
-(void)setOrgType:(NSString *)orgType{
    _orgType = orgType;
    NSLog(@"%@",_orgType);
}

-(void)alertSomes:(NSString *)msg{
    PopulationContainerViewController *container = (PopulationContainerViewController *)self.theDelete;
    [container turnToIndex:[container.ctlArray indexOfObject:self] andAlert:msg];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.peopleRelated = [NSMutableArray array];
    self.financialRelated = [NSMutableArray array];
    self.btnsArray = [NSMutableArray array];
    [self loadData];
}

-(void)loadData{
    //获取数据，然后更新布局
    [self beginLoading];
    [[NetWorkerManager sharedInstance]postWithPath:self.path parameter:nil completeBlock:^(NSDictionary *source) {
        [self endLoading];
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:NSClassFromString(self.itemCls)];
        if (model.success) {
            NSArray *dt = [model.data objectForKey:@"data"];
            NSDictionary *last = dt.lastObject;
            NSDictionary *subType = [last objectForKey:@"subTypes"][0];
            NSArray *orgs = subType[@"orgs"];
            self.orgs = [orgs mutableCopy];
            CGFloat height = 0;
            self.peopleRelated = [model.list mutableCopy];
            for (TypeListModel *m in model.list) {
                for (SubTypeItemModel *submodel in m.children) {
                    [self.financialRelated addObject:submodel];
                }
                UIView *block = [self blockWithTypeModel:m];
                block.top = height;
                height = block.bottom + 20;
                [self.scroll addSubview:block];
                self.scroll.contentSize = CGSizeMake(0, height);
                if ([model.list.lastObject isEqual:m]) {
                    if ([m.name isEqualToString:@"铁路沿线重点人员"]) {
                        self.descLabel = [[UILabel alloc]init];
                        self.descLabel.font = [UIFont systemFontOfSize:14];
                        self.descLabel.text = @"未选择";
                        [self.orgs enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                            if ([obj[@"id"] isEqualToString:self.selectedOrgId]) {
                                self.descLabel.text = obj[@"orgName"];
                            }
                        }];
                        self.descLabel.frame = CGRectMake(0, 0, [self.descLabel textSize].width, [self.descLabel textSize].height);
                        self.descLabel.top = 54;
                        self.descLabel.left = self.view.width - self.descLabel.width - 30;
                        [block addSubview:self.descLabel];
                        if (!self.cantEdit) {
                            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showArea:)];
                            [block addGestureRecognizer:tap];
                        }
                    }
                }
            }
        }else{
            [self alertSome:model.msg];
        }
    } failBlock:^(NSInteger code) {
        [self endLoading];
        [self alertSome:kNetWorkFail];
    }];
}

-(void)showArea:(UITapGestureRecognizer *)tap{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    for (NSDictionary *element in self.orgs) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:element[@"orgName"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.selectedOrgId = element[@"id"];
            self.descLabel.text = element[@"orgName"];
            self.descLabel.frame = CGRectMake(self.descLabel.left, 54, [self.descLabel textSize].width, [self.descLabel textSize].height);
            self.descLabel.left = self.view.width - 30 - [self.descLabel textSize].width;
        }];
        [alert addAction:action];
    }
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}

-(UIView *)blockWithTypeModel:(TypeListModel *)model{
    UIView *tray = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 0)];
    tray.backgroundColor = [UIColor whiteColor];
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.font = [UIFont boldSystemFontOfSize:14];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.text = model.name;
    CGSize titleSize = [titleLabel textSize];
    titleLabel.frame = CGRectMake(15, 22 - titleSize.height / 2, titleSize.width, titleSize.height);
    [tray addSubview:titleLabel];
    UIView *line = [[UIView alloc]init];
    line.backgroundColor = [UIColor colorWithHexString:@"EEF2F4"];
    line.frame = CGRectMake(0, 44, self.view.width, 0.5);
    [tray addSubview:line];
    for (SubTypeItemModel *child in model.children) {
        UIButton *button = [self buttonWithModel:child index:[model.children indexOfObject:child]];
        [tray addSubview:button];
        [self.btnsArray addObject:button];
        tray.height = button.bottom + 10;
    }
    return tray;
}


-(UIButton *)buttonWithModel:(SubTypeItemModel *)model index:(NSInteger)index{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:model.name forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:12];
    button.titleLabel.numberOfLines = 0;
    CGFloat x = (ScreenWidth / 2) * (index % 2 == 0 ? 0 : 1);
    CGFloat y = 44 + 10 + 30 * (index / 2);
    CGSize titleSize = [model.name caculateSizeWithFont:[UIFont systemFontOfSize:12] MaxSize:CGSizeMake(150, 1000)];
    CGFloat btnHeight = titleSize.height > 25 ? titleSize.height : 25;
    [button setImageEdgeInsets:UIEdgeInsetsMake(0, -2, 0, 2)];
    [button setTitleEdgeInsets:UIEdgeInsetsMake(0, 2, 0, -2)];
    button.frame = CGRectMake(x, y, titleSize.width + 25, btnHeight);
    [button setImage:[UIImage imageNamed:@"icon_choose_selected"] forState:UIControlStateSelected];
    [button setImage:[UIImage imageNamed:@"icon_choose_normal"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(selectMySelf:) forControlEvents:UIControlEventTouchUpInside];
    [self.selectedBusiness enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isEqualToString:model.subTid]) {
            button.selected = YES;
        }
    }];
    return button;
}

-(void)selectMySelf:(UIButton *)button{
    if (self.cantEdit) {
        return;
    }
    button.selected = !button.selected;
    NSInteger index = [self.btnsArray indexOfObject:button];
    SubTypeItemModel *model = [self.financialRelated objectAtIndex:index];
    
    if (!self.multiSelect) {
        if ([self.theDelete respondsToSelector:@selector(fetchModel:)]) {
            if (self.needParentInfo) {
                for (TypeListModel *parent in self.peopleRelated) {
                    if ([parent.tid isEqualToString:model.parentId]) {
                        NSDictionary *info = @{@"parent":parent,@"sub":model};
                        [self.theDelete fetchModel:info];
                        break;
                    }
                }
                
            }else{
                [self.theDelete fetchModel:model];
            }
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
    }
    if (!self.multiSelect) {
        for (UIButton *btn in self.btnsArray) {
            btn.selected = NO;
        }
    }else{
        if (self.selectedBusiness) {
            if (button.selected) {
                [self.selectedBusiness addObject:model.subTid];
            }else{
                [self.selectedBusiness enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([obj isEqualToString:model.subTid]) {
                        [self.selectedBusiness removeObject:obj];
                    }
                }];
            }
        }else{
            self.selectedBusiness = [NSMutableArray array];
            if (button.selected) {
                [self.selectedBusiness addObject:model.subTid];
            }else{
                [self.selectedBusiness enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([obj isEqualToString:model.subTid]) {
                        [self.selectedBusiness removeObject:obj];
                    }
                }];
            }
        }
    }
}

@end
